package com.emit.utils;/**
 * @author : 郑大哥
 * @date :
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author zhengshuai
 */
@Service
public class HttpUtils {

    @Autowired
    @Qualifier("restTemplate")
    private  RestTemplate restTemplate;


    // Get请求
    public String Get(String url, Map<String, Object> params) {
        String uri = buildUri(url, params);
        ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
        return response.getBody();
    }

    // Post请求(JSON请求头)
    public String JPost(String url, Map<String, Object> params) {
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, jsonHeaderBuilder());
        ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
        return response.getBody();
    }

    // Post请求(URL请求头)
    public String UPost(String url, MultiValueMap<String, String> params) {
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, urlHeaderBuilder());
        ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
        return response.getBody();
    }

    // 拼接Url和参数
    private String buildUri(String url, Map<String, Object> params) {
        StringBuilder sb = new StringBuilder(url);
        sb.append("?");
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    // 构建Url请求头
    private HttpHeaders urlHeaderBuilder() {
        HttpHeaders h = new HttpHeaders();
        h.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        return h;
    }

    // 构建Json请求头
    private HttpHeaders jsonHeaderBuilder() {
        HttpHeaders h = new HttpHeaders();
        h.setContentType(MediaType.APPLICATION_JSON);
        return h;
    }


}